package com.dmooo.ymx.login;

import android.app.Activity;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.dmooo.ymx.CaiNiaoApplication;
import com.dmooo.ymx.R;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.common.ACache;
import com.dmooo.ymx.common.LogUtils;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.common.T;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.github.anzewei.parallaxbacklayout.ParallaxHelper;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.tencent.connect.UserInfo;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class WelActivity extends BaseActivity implements IUiListener {
    @BindView(R.id.tv_register)
    TextView tv_register;
    private ACache mAcache;
    private SendAuth.Req req;
    private Tencent tencent;
    public static Activity activity;

    @Override
    protected void initUI() {
        setContentView(R.layout.ac_welone);
        ButterKnife.bind(this);
        ParallaxHelper.disableParallaxBack(this);
        activity = this;
    }

    @Override
    protected void initData() {
        req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "hkx" + System.currentTimeMillis();
        req.transaction = "login";
        mAcache = ACache.get(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ("cancle".equals(SPUtils.getStringData(this, "wx_code", ""))) {
            T.showShort(this, "取消微信登录");
        } else if (!"".equals(SPUtils.getStringData(this, "wx_code", ""))) {
//            T.showShort(this,"微信code去获取openid");
            getOpenId(SPUtils.getStringData(this, "wx_code", ""));
        }
        SPUtils.saveStringData(this, "wx_code", "");
    }

    private void getOpenId(String code) {
        Log.d("dsfasdf",Constants.WX_APP_ID);
        RequestParams params = new RequestParams();
        HttpUtils.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constants.WX_APP_ID+"&secret="+Constants.WX_APP_SECRET+"&code=" + code + "&grant_type=authorization_code", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if (responseString.contains("errcode")) {
                    T.showShort(WelActivity.this, "授权失败");
                    return;
                }
                try {
                    JSONObject object = new JSONObject(responseString);
                    checkIsBind("wx", object.getString("openid"), object.getString("access_token"));
                } catch (JSONException e) {
                    e.printStackTrace();
                    T.showShort(WelActivity.this, "授权失败");
                }
            }

            @Override
            public void onStart() {
                super.onStart();
            }
        });
    }

    private void checkIsBind(final String type, final String openId, final String access_token) {
        RequestParams params = new RequestParams();
        params.put("type", type);
        params.put("openid", openId);
        HttpUtils.post(Constants.IS_BIND, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    if (0 == code) {
                        JSONObject jsonObject2 = jsonObject.getJSONObject("data");
                        String uid = jsonObject2.optString("uid");
                        String token = jsonObject2.optString("token");
                        mAcache.put(Constants.TOKEN, token);
                        SPUtils.saveStringData(WelActivity.this, Constants.TOKEN, token);
                        SPUtils.saveStringData(WelActivity.this, Constants.UID, uid);
                        SPUtils.saveStringData(WelActivity.this, "is", "1");
                        finish();
                        SPUtils.saveStringData(WelActivity.this, "is", "1");
                    } else {
                        getAvatarInfo(type, openId, access_token);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });
    }

    private void getAvatarInfo(final String type, final String openId, final String access_token) {
        if ("qq".equals(type)) {
            UserInfo info = new UserInfo(this, tencent.getQQToken());
            info.getUserInfo(new IUiListener() {
                @Override
                public void onComplete(Object o) {
                    final String nickname = ((JSONObject) o).optString("nickname");
                    final String headImg = ((JSONObject) o).optString("figureurl_qq_2");
                    showTipDialog2("登录提示", Html.fromHtml("暂未绑定手机号"), new onClickListener() {
                        @Override
                        public void onClickSure() {
                            Intent intent = new Intent(WelActivity.this, BindPhoneActivity.class);
                            intent.putExtra("type", type);
                            intent.putExtra("openid", openId);
                            intent.putExtra("name", nickname);
                            intent.putExtra("avatar", headImg);
                            startActivity(intent);
                        }
                    }, "去绑定");
                }

                @Override
                public void onError(UiError uiError) {
                }

                @Override
                public void onCancel() {
                }
            });
        } else {
            RequestParams params = new RequestParams();
            HttpUtils.get("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId, params, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    if (responseString.contains("errcode")) {
                        T.showShort(WelActivity.this, "授权失败");
                        return;
                    }
                    try {
                        final JSONObject object = new JSONObject(responseString);
                        final String nickname = object.getString("nickname");
                        final String avatar = object.getString("headimgurl");
                        showTipDialog2("登录提示", Html.fromHtml("暂未绑定手机号"), new onClickListener() {
                            @Override
                            public void onClickSure() {
                                Intent intent = new Intent(WelActivity.this, BindPhoneActivity.class);
                                intent.putExtra("type", type);
                                intent.putExtra("openid", openId);
                                intent.putExtra("name", nickname);
                                intent.putExtra("avatar", avatar);
                                startActivity(intent);
                            }
                        }, "去绑定");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        T.showShort(WelActivity.this, "授权失败");
                    }
                }

                @Override
                public void onStart() {
                    super.onStart();
                }
            });
        }
    }

    @Override
    protected void initListener() {
        //注册
        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(RegisterActivity.class);
            }
        });
    }
    @Override
    public void onBack(View v) {

    }
    @OnClick({R.id.tv_login_wx,R.id.tv_login_phone,R.id.btn_one1,R.id.btn_one2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_one2:
            case R.id.tv_login_wx:
                if (getPackageManager().getLaunchIntentForPackage("com.tencent.mm") == null) {
                    T.showShort(this, "请安装微信客户端");
                    return;
                }
                CaiNiaoApplication.api.sendReq(req);
                break;
            case R.id.btn_one1:
            case R.id.tv_login_phone:
                startActivity(new Intent(this,LoginActivity.class));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, this);
    }

    /**
     * 腾讯授权回调
     *
     * @param o
     */
    @Override
    public void onComplete(Object o) {
        if (o.toString().contains("openid")) {
            try {
                JSONObject object = new JSONObject(o.toString());
                checkIsBind("qq", object.getString("openid"), object.getString("access_token"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(UiError uiError) {
        T.showShort(this, "登录异常");
    }

    @Override
    public void onCancel() {
        T.showShort(this, "取消操作");
    }
}
